<?php
class News extends CI_Controller{


	function __construct(){
		parent::__construct();
	}

	/**
	 * Load main news page (latest results only)
	 **/
	function index(){
		$this->load->model('news_model');
		$news = $this->news_model->get_news();

		$params = array();
		if($news != false){
			$params['news_items']=$news;
		}

		$params['subview'] = 'subview/news_view';
		$this->load->view('homepage_view', $params);
	}

	function post(){
		$params['subview'] = 'subview/news_add_view';
		$this->load->view('homepage_view', $params);
	}

	/**
	 * Load news add/post form
	 **/
	function add(){
		if ($this->validate_news()){

			$input_data = array(
				'content' 	=> $this->input->post('content', true),
				'title'	 	=> $this->input->post('title', true),
				'author'	=> $this->session->userdata('account')
			);

			$this->load->model('news_model');
			$news = $this->news_model->add_news($input_data);

			if (!$news){
			} else {

				redirect('/news');
			}

		} else {
			$params['subview'] = 'subview/news_add_view';
			$this->load->view('homepage_view', $params);
		}
	}

	function validate_news(){
		$this->load->library('form_validation');

		//Enforce rules of form fields.
		$this->form_validation->set_rules('title', 'Title', 'trim|required|max_length[64]');		

		return $this->form_validation->run();
	}

	/**
	 * Load news archives (one page at a time)
	 **/
	function archives($page){
		$this->load->model('news_model');
		$news = $this->news_model->get_archives($page);
		if ($news){
			$params['archive'] = $page;
			if (($page*$this->news_model->archived_news_per_page) >= $this->news_model->max){
				$params['end'] = true;
			}
		}


		$params['news_items']=$news;
		$params['subview'] = 'subview/news_view';
		$this->load->view('homepage_view', $params);
	}

	/**
	 * Opens the add news page to edit an existing event entry
	 *
	 */
	function edit($id = 0){
		if ($this->gateway_model->is_admin() && $id != 0){
			$this->load->model('news_model');
			$news = $this->news_model->get_post($id);
			if (isset($news)){
				$params['news'] = $news;
				$params['subview'] = 'subview/news_add_view';
				$this->load->view('homepage_view', $params);
			}
		} else {
			redirect('/news/');
		}
	}

	/**
	 * Updates changes to an event
	 */
	function change(){
		if ($this->validate_news()){
			$data = array (
				'id' => $this->input->post('id'),
				'content' => $this->input->post('content', true),
				'title' => $this->input->post('title')
			);

			$this->load->model('news_model');
			$error = $this->news_model->update_post($data);

			if ($error != ''){
				redirect('/news/edit/' .$data['id']);
				echo $error;
			}

			redirect('/news');
		} else {
			redirect('/news/edit/' .$data['id']);
		}

	}
}
